//
//  ArticleView.m
//  Final
//
//  Created by student14 on 2021/12/14.
//  Copyright © 2021 Lenrony. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "ArticleView.h"
#import "../DetailViewController.h"
#import "../HomeViewController.h"
#import "../MyArticlesViewController.h"
#import "MJRefresh.h"

@interface ArticleView ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>{
    
    float screen_width;
    float screen_height;
}

@property(strong, nonatomic) NSMutableArray *articles;//存储帖子的数组
@property(strong, nonatomic) NSMutableArray *showingArticles;
@property(strong, nonatomic) NSMutableArray *rawUsers;
@property(strong, nonatomic) NSMutableArray *showingRawUsers;
@property NSInteger currentCellCount;

@property(strong, nonatomic) UIViewController* svc;

@end

@implementation ArticleView

- (ArticleView *) initWithViewController: (UIViewController *)svc
                             andRawUsers: (NSMutableArray *)rawUsers
                             andArticles: (NSMutableArray *)articles
{
    self = [super init];
    screen_width = [UIScreen mainScreen].bounds.size.width;
    screen_height = [UIScreen mainScreen].bounds.size.height;
    [self setFrame:CGRectMake(0, 0, screen_width, screen_height)];
    
    self.svc = svc;
    self.rawUsers = rawUsers;
    self.articles = articles;
    
    [self setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"gray.png"]]];
    [self loadCollectionViews];
    return self;
}

- (void)loadCollectionViews {
    if (self.showingArticles == nil) {
        self.showingArticles = [[NSMutableArray alloc] init];
    }
    if (self.showingRawUsers == nil) {
        self.showingRawUsers = [[NSMutableArray alloc] init];
    }
    self.currentCellCount = MIN(self.articles.count, 6);
    // 初始时先加载几个article
    for (int i = 0; i < _currentCellCount; i++) {
        [self.showingArticles addObject:self.articles[i]];
        [self.showingRawUsers addObject:self.rawUsers[i]];
    }
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.minimumLineSpacing = 5;
    layout.itemSize = CGSizeMake(screen_width, 450);
    layout.sectionInset = UIEdgeInsetsMake(3, 0, 0, 0);
    
    _articlesView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, screen_width, 600) collectionViewLayout:layout];
    _articlesView.backgroundColor = [UIColor clearColor];
    _articlesView.scrollEnabled = YES;
    _articlesView.userInteractionEnabled = YES;
    
    [_articlesView setDelegate:self];
    [_articlesView setDataSource:self];
    [_articlesView registerClass:[ArticleCell class] forCellWithReuseIdentifier:@"Article"];
    
    if ([self.svc isKindOfClass:[HomeViewController class]]) {
        _articlesView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.articlesView.mj_header endRefreshing];
                [(HomeViewController *)self.svc updateCollectionView];
            });
        }];
    }
    else if ([self.svc isKindOfClass:[MyArticlesViewController class]]) {
        _articlesView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.articlesView.mj_header endRefreshing];
                [(MyArticlesViewController *)self.svc updateCollectionView];
            });
        }];
    }
    
    _articlesView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.articlesView.mj_footer endRefreshing];
            if (self.articles.count > self.currentCellCount) {
                NSInteger tempCount = MIN(6, self.articles.count - self.currentCellCount);
                for (NSInteger i = self.currentCellCount; i < self.currentCellCount+tempCount; i++) {
                    [self.showingArticles addObject:self.articles[i]];
                    [self.showingRawUsers addObject:self.rawUsers[i]];
                }
                self.currentCellCount += tempCount;
                [self willRemoveSubview:self.articlesView];
                [self.articlesView reloadData];
                [self addSubview:self.articlesView];
            }
        });
    }];
    
    [self addSubview:_articlesView];
}

- (void) updateCollectionViewWithArticles:(NSMutableArray *)articles
                              andRawUsers:(NSMutableArray *)rawUsers
{
    [self.articles removeAllObjects];
    [self.rawUsers removeAllObjects];
    for (int i = 0; i < articles.count; i++) {
        [self.articles addObject:articles[i]];
        [self.rawUsers addObject:rawUsers[i]];
    }
    [self.showingArticles removeAllObjects];
    [self.showingRawUsers removeAllObjects];
    self.currentCellCount = MIN(self.articles.count, 6);
    for (int i = 0; i < self.currentCellCount; i++) {
        [self.showingArticles addObject:self.articles[i]];
        [self.showingRawUsers addObject:self.rawUsers[i]];
    }
    [self.articlesView reloadData];
}

// 代理方法
- (UICollectionViewCell *)collectionView: (UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    ArticleCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Article" forIndexPath:indexPath];
    [cell setArticle:_showingArticles[indexPath.item] andRawUser:_showingRawUsers[indexPath.item] andViewController:_svc];
    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.currentCellCount;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    Article *art = _showingArticles[indexPath.item];
//    NSString *tempStr = [art.content stringByReplacingOccurrencesOfString:@"\n" withString:@" "];
    NSString *tempStr = art.content;
    CGSize size = [tempStr boundingRectWithSize:CGSizeMake(screen_width-60, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20]} context:nil].size;
    size = CGSizeMake(screen_width, size.height + 85);
    return size;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    DetailViewController *dvc = [[DetailViewController alloc] initWithArticle:_showingArticles[indexPath.item]];
    [_svc.navigationController pushViewController:dvc animated:YES];
}

@end
